/**
 * Description: 客户端
 * File: client.c |Time: 2021-06-28 04:49
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define ERR(msg) do{        \
    perror(msg);            \
    printf("err: %s:%s:%d\n", __FILE__, __func__, __LINE__); \
    return EXIT_FAILURE;    \
}while(0)

#define LISTEN_BACKLOG 10
#define BUFSIZE  128

int main(int argc, const char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s <ip> <port>\n", argv[0]);
        return EXIT_FAILURE;
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    const char *ip = argv[1];
    const int port = atoi(argv[2]);

    if (socket < 0) {
        ERR("socket");
    }

    struct sockaddr_in serveraddr; 
    socklen_t addrlen = sizeof(serveraddr);
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(port);
    serveraddr.sin_addr.s_addr = inet_addr(ip);
    
    int res;
    char buf[BUFSIZE] = {0};
    res = connect(sockfd, (struct sockaddr *)&serveraddr, addrlen);
    if (res < 0) {
        ERR("connect error");
    }

    while(1) {
        memset(buf, 0, sizeof(buf));
        printf("[to server] ");
        fgets(buf, BUFSIZE, stdin);
        buf[strlen(buf) - 1] = '\0';
        
        res = send(sockfd, buf, BUFSIZE, 0);
        if (res < 0) {
            ERR("send error");
        }
    }
    
    return 0;
}


